package rabbitmq.work;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT); //需要提前开放端口号
        connectionFactory.setUsername(Constants.USER_NAME); //账号
        connectionFactory.setPassword(Constants.PASSWORD); //密码
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST); //虚拟主机
        Connection connection = connectionFactory.newConnection();
        //2.开启信道
        Channel channel = connection.createChannel();
        //3.声明队列

        /**
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
         *                                                Map<String, Object> arguments)
         * 参数说明:
         * queue:队列名称
         * durable:可持久化 true-设置队列为持久化, 待久化的队列会存盘,服务器重启之后, 消息不丢失。
         * exclusive:是否独占,只能有⼀个消费者监听队列
         * autoDelete:是否⾃动删除, 当没有Consumer时, ⾃动删除掉
         * arguments 参数
         */
        channel.queueDeclare(Constants.WORK_QUEUE, true, false, false, null);

        //4.消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("Consumer2 收到消息: " + new String(body));
            }
        };

        channel.basicConsume(Constants.WORK_QUEUE, true, consumer);

        //5.释放资源
//        channel.close();
//        connection.close();
    }
}
